var arrayAns = {}; //answers unparsed
var arrayAnsDrop = {}; // parsed answers for drag and drop
var arrayAnsToDrop= {};

var notes=[]; // for imgNote
var divs=[]; // divs created by imgNote

var lastFound; // flag to determine if last interaction was successfull
var clickOn; // to determine if a click has been performed on a interactive item
var clickFlag; // flag to store id of a clicked item
var clickObj; // interactive object last clicked on

var feedbackbox; // store id of feedback area
var mouseX, mouseY; //store location of mouse when items are clicked

var completedActivity =false; //boolean
var completedGroup =false; //for groups of questions, to display intermediate feedback
var postponeFinalFB = false; // flag for postponed final feedback, relegated to click binds to call
var initedCount = false; // for feedback purposes, to signal all answers have been counted

// MULTILANG
var str_verify="";
var str_correct = "";
var str_reinit = "";

//EXO TYPE HELPER
var exoTypes; //string of types of exercices in this 
var exoType; //array

//DEBUG HELPERS
var debugHelper =false;
var debugDispCount = 0;


isExoType = function(type){
	var found = false;
	for(var i=0; i< exoType.length; i++){
		if(exoType[i].toLowerCase() == type.toLowerCase())
			found =true;
	}
	return found;
}

getExoType = function(){
	alert(exoTypes);
}

$(document).ready(function(){
	fetchAnswers();
	parseAnswers();
	initHint();
	initLang();
	
	exoTypes= $('#baseType').text();
	exoType = exoTypes.split(" ");
	var toCorrect = false;
	
	for(var i=0; i< exoType.length; i++){
		switch(exoType[i]){
			case "inline" : {
				initInlineExo();
				toCorrect = true;
			}
			break;
			case "fill-in" : {
				initCheckSpelling();
				toCorrect = true;
			}
			break;
			case "directedMatch" : {
				initMultiDrop();
				toCorrect = true;
			}
			break;
			case "directedPair" : {
				initDrop();	
				initTableSort();
				toCorrect = true;
				// alert("directed pair");
			}
			break;
			case "directedPairAbacus" : {
				initDrop();	
				initTableSort();
				toCorrect = true;
			}
			break;
			case "directedPairMatching" : {
				initMatching();
				initDrop();
				toCorrect = true;
			}
			break;
			case "tableSort" : {
				initDrop();	
				initTableSort();
				toCorrect = true;
			}
			break;
			case "matching" : {
				initMatching();
				toCorrect = true;
			}
			break;
			case "imageMatch" : {
				initImageDrop();
				initDrop();
				toCorrect = true;
			}
			break;
			case "multipleChoice" : {
				initMultiChoice();
				toCorrect = true;
			}
			break;
			case "flashMedia" : {
				initParamFlash();
			}
			break;
		}
	}
	
	if(toCorrect) initCorrectForm();
	
	initReinitForm();
	 // TO REORDER
	initRandom();
	initFB();
	initMovable();
	
	clarify();
	// switchAddr();
	beautify();
	
});

// ************* BEGIN TWEAKS *************
beautify = function(){
	$(".prompt").css('opacity', 0.7);
	$("<span class='positive'/>").remove();
}

switchAddr = function(){
	$("object").each(function(){
		if( $(this).attr("type")=="application/x-shockwave-flash"){
			$("param", this).each(function(){
				if($(this).attr('name')=="FlashVars"){
					// alert("found");
					var addr = $(this).attr("value");
					var modAddr = addr.split("mp3=")[1];
					$(this).attr("value", "http://labas.com"+modAddr);
				}
			});
		}
	});
}

clarify = function(){
	var perline = 10;
	var numSpans = $('#global > .exos').find("span").length;
	var tmp = perline;
	while(tmp < numSpans){
		$('#global > .exos').find("span:nth-child("+tmp+")").after("<br/>");
		tmp+=perline;
	}
}

initLang = function(){
	if($('#lang').text()=="fr"){
		str_verify="Vérifier";
		str_correct = "Corrigé";
		str_reinit = "Réinitialiser";
	}
	if($('#lang').text()=="es"){
		str_verify="Convalida";
		str_correct = "Corregi";
		str_reinit = "Reset";
	}
	if($('#lang').text()=="it"){
		str_verify="Controllo";
		str_correct = "Correzione";
		str_reinit = "Reset";
	}
}

// ************* END TWEAKS *************

initFB = function(){
	if($('#feedbackType').text()=="float")
		floatFB();
	
	if($('#feedbackType').text()=="bottom")
		bottomFB();
	
	feedbackbox="#fb";
}

initCorrectForm = function(){
	$('#correction').append('<form id="verification" method="get" action="">'+
							'<input name="verification" value="'+str_verify+'" onclick="" type="submit"/>'+
							'</form>');
	$('#correction').append('<form id="correct" method="get" action="">'+
							'<input name="correction" value="'+str_correct+'" onclick="" type="submit"/>'+
							'</form>');
	
	
	initCorrection();
	initVerification();
}

initReinitForm = function(){
	if($('#baseType').text()!="")
		$('#correction').append('<form id="reinit" method="get" action="">'+
									'<input name="reinit" value="'+str_reinit+'" onclick="window.location.reload()" type="submit"/>'+
							'</form>');
}

/************** ANSWER WATCHING HELPERS ***************/

isCorrectMulti = function(){
	if(!isExoType("multipleChoice")) return true;
	
	return $('.multi').length == $('.multi.success').length;
	
}

isCorrectInline = function(){
	if(!isExoType('inline')) return true;
	
	return $('.inline-exe').length == $('.success').length && $('.inline-exe').length != 0;
}

isCorrectFillin = function(){
	if(!isExoType("fill-in")) return true;
	
	return $('.gap').length == $('.success').length && $('.gap').length != 0;
}

isCorrectMatching = function(){
	if(!isExoType("matching")) return true;
	
	return $('.matchend').length == ($('.found').length)/2;
}

isCorrectMultiDrop = function(){
}

isCorrectDND = function(){
	$('.exos').each(function(){
		var totalNumAns;
		if(!initedCount){
			totalNumAns = $(this).find('.ui-draggable',this).length ;
			$(this).attr('totalNumAns', totalNumAns);
			initedCount = true;
		}
		else{
			totalNumAns = $(this).attr('totalNumAns');
		}
		var totalUsed = $(this).find('.used',this).length;
		
		if(totalNumAns == totalUsed && totalUsed != 0 || totalNumAns == 0
				&& isExoType("inline") && isExoType("fill-in") ) { // && isExoType("matching")){ WHAT..???
			$(this).parent().find('.feedback').removeClass('invisible');
			return true;
		}
		
		else return false;
	});
}


watchAnswerGroups= function(){
	
	$('.answergroup').each(function(){
		var numAns = $(this).find('span.block',this).length;
		var used = $(this).find('span.used',this).length;
		// alert("ans for this group : " + numAns + "    used: "+ used);
		if(numAns == used && used != 0 ){ //|| numAns == 0 FIXING ?
			// $(this).parent().find('.feedback').removeClass('invisible');
			completedGroup=true;
			//alert("completed code1, numAns="+numAns+" used="+used);
		} 
	});
	
	$('.exos').each(function(){
		var totalNumAns;
		if(!initedCount){
			totalNumAns = $(this).find('.ui-draggable',this).length ;
			$(this).attr('totalNumAns', totalNumAns);
			initedCount = true;
		}
		else{
			totalNumAns = $(this).attr('totalNumAns');
		}
		var totalUsed = $(this).find('.used',this).length;
		
		// alert('ans='+totalNumAns+" used="+totalUsed);
		if(totalNumAns == totalUsed && totalUsed != 0 || totalNumAns == 0
				&& isExoType("inline") && isExoType("fill-in") && isExoType("matching")){
			// alert("ended");
			$(this).parent().find('.feedback').removeClass('invisible');
			completedActivity=true;
			// alert("completed code2");
			finalFeedback();
		}
	});
	
	if( $('.inline-exe').length == $('.success').length && $('.inline-exe').length != 0){
		// $(".globalFB").removeClass("invisible");
		completedActivity=true;
		// alert("completed code3");
		finalFeedback();
	}
	
	if( $('.gap').length == $('.success').length && $('.gap').length != 0){
		// $(".globalFB").removeClass("invisible");
		completedActivity=true;
		// alert("completed code4");
		finalFeedback();
	}
	
	if(isExoType("matching")){
		if( $('.matchend').length == ($('.found').length)/2 ){
			// alert( "ends="+$('.matchend').length + " found="+$('.found').length);
			completedActivity=true;
			finalFeedback();
		}
	}
	
//	if(	isCorrectMulti() ){
		// alert( "ends="+$('.matchend').length + " found="+$('.found').length);
//		completedActivity=true;
//		finalFeedback();
//	}
	
}

finalFeedback = function(){
	if(!completedActivity){
		if($(".globalFBNeg").length!=0){
			if(clickOn){
				postponeFinalFB = true;
			}
			else{
				centerPopup(".globalFBNeg");  
				loadPopup(".globalFBNeg");
			}
		}
	}
	
	else if($(".globalFB").length!=0){
		if(clickOn){
			postponeFinalFB = true;
		}
		else{
			centerPopup(".globalFB");  
			loadPopup(".globalFB");
		}
	}
	
}

feedback = function(content, state){
	$('span.positive, span.negative').each(function(){
		$(this).addClass('invisible');
	});
	$(feedbackbox).html("<p>"+ content +"</p>");
	if(state)
		$(feedbackbox).effect('bounce');
	else if(!state)
		$(feedbackbox).effect('shake');
}

floatFB = function(){
	$('.listing').append("<tr style='height:30px; overflow:visible;'><td colspan='3'><div id='fb' class='staticFBbox'></div></td></tr>");
	// $('.exos').append("<div id='fb' class='staticFBbox'></div>");
	// var pos = $(window).height();
	// $('#fb').css({top: pos-150 + 'px'});
}

bottomFB = function(){
	$('.exos').append("<div id='fb' class='feedback-area'></div>");
}

fetchAnswers = function(){
	$("div.answer-set").find('li').each(function() { 
		var tmp= $(this).text();
  		arrayAns[tmp] = tmp;
	});
}

jQuery.fn.sort = function() {
        return this.pushStack( jQuery.makeArray( [].sort.apply( this, arguments ) ) );

};

initRandom = function(){
	$('.random').children().sort(function(a, b) { 
		var rand=Math.floor(Math.random()*2) - Math.floor(Math.random()*2);
		return rand;
	}).prependTo('#answergroup'); 

}

initHint = function(){
	//non persistent hover
	$("a.hint").tooltip({ 
    	bodyHandler: function() { 
        	return $("#"+$(this).attr("name")).html(); 
    	}, 
	    showURL: false 
	});
	
	//persistent popup window
	$(".hover-content, .globalFB, .globalFBNeg").prepend("<a class='popupContactClose'>x</a>  ");
	
	$("a.initHover").click(function(){  
		centerPopup("#"+$(this).attr("name"));  
		loadPopup("#"+$(this).attr("name")); 
		return false;
	});

	//CLOSING POPUP
	//Click the x event
	$(".popupContactClose").click(function(){
		disablePopup(currentPopup);
		return false;
	});
	//Click out event
	$("#backgroundPopup").click(function(){
		disablePopup(currentPopup);
		return false;
	});
	//Press Escape event
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup(currentPopup);
		}
	});
}

initMovable = function(){
	var pos = $(window).height();
	$('.movable').css({top: pos-450 + 'px', position:"fixed"});
	// $('.movable').draggable({revert:false, 
	// 						cursor: 'move'});
}

/**************************************
// answer parsing
/**************************************/

parseAnswers= function(){
	for(var key in arrayAns){
		var tmp_array= key.split(" "); //gives an array with 2+ items : key value
		
		arrayAnsToDrop[tmp_array[0]] = "";
		
		for(i=1; i<tmp_array.length; i++){ // this is done in case of multiple placements (drop zones) for one answer
			if(!arrayAnsDrop[tmp_array[i]])
				arrayAnsDrop[tmp_array[i]]= ""; //initialize space
				
			arrayAnsDrop[tmp_array[i]] += tmp_array[0] +" "; // drop zone(s) -> answer-id
			
			arrayAnsToDrop[tmp_array[0]] += tmp_array[i]; i==tmp_array.length-1? true : arrayAnsToDrop[tmp_array[0]] += "&";  //  answer-id -> drop zone(s) 
			// adds one more space and requires parsing
		}
	}
}


/**************************************
// inline and correction
/**************************************/

initInlineExo = function(){
	arrayAnsIn= fetchAnswersIEf();
	
	$(".inline-exe").click( function(){
			var answer = $(this).selectedValues();
			// alert("-"+arrayAnsIn[answer]+"-");
			if(answer=='-1'){
				doNeutral($(this));
				//feedback("", null);
			}	
			else{
				var found = false;
				for(value in arrayAnsIn){
					if(arrayAnsIn[value] == answer){
						var content = $(this).next('.feedback').find(".positive").html();
						feedback(content, true);
						doSuccess($(this));
						found = true;
					}
				}
				if(!found){
					var content = $(this).next('.feedback').find(".negative").html();
					feedback(content, false);
					doFail($(this));
				}
				$(this).blur();
			}
			
			watchAnswerGroups();
	});
}

fetchAnswersIEf = function(){
	arrayAnsIn = [];
	$("div.answer-set").find('li').each(function() { 
		var tmp= $(this).text().split(" ")[0];
  		arrayAnsIn.push(tmp);
	});
	return arrayAnsIn;
}

correctInline = function(){
	var once=false;
	var one=false;
	$(".inline-exe:not(.success)").each(function(){
			arrayAnsIn= fetchAnswersIEf();
			var answer;
			$('option', this).each(function(){
				var val = $(this).val().split(" ")[0];
			
				for(i in arrayAnsIn){
					if(arrayAnsIn[i]==val){
						// alert($(this).text());
						answer=$(this).text();
						// $(this).parent().next('span').removeClass('invisible').addClass('corrected').text(answer);
						$(this).parent().parent().addClass('corrected').text(answer);
					}
				}
			});
			$(this).remove();
		});
}

/**************************************
// multi choice
/**************************************/

initMultiChoice = function(){
	$('.multi :input').click(function(){
		$(this).parent().find('input').each(function(){
			$(this).parent().removeClass('fail');
			$(this).parent().removeClass('success');
			//doNeutral($(this).parent());
		});
		
		if( arrayAns[$(this).attr('id')] == $(this).attr('id') ){
			doSuccess($(this).parent());
		}
		else{
			doFail($(this).parent());
		}
		
	});
}

correctMultiChoice = function(){
	for(var key in arrayAns){
		$('input#'+key+':not(.success)').each(function(){
			// alert("found");
			$(this).parent().select();
			$(this).parent().addClass("corrected");
		});
	}
}

/**************************************
// drag and drop
/**************************************/

initDropCommon = function(){
	$(".block").draggable({revert:true, 
							distance: 20, 
							cursor: 'move', 
							top: -5, left: -5}); 
	
 	$(".block-i, .block-h").draggable({revert:true, 
							distance: 20, 
							helper: 'clone', 
							appendTo: 'body', 
							cursor: 'move', 
							top: 0, left: 0});
							
	if(isExoType("directedMatch"))
		$(".block, .block-i, .block-h").each(function(){
			var id = $(this).attr('id');
			var targetCount = arrayAnsToDrop[id].split("&").length;
			$(this).attr('targetCount', targetCount);
			$(this).attr('dropCount', 0);
			$(this).attr('dropSpots', "");
		});
}

initDrop = function(){
    initDropCommon();
	initFBDND();
    var droppable = $(".drop, .drop-camo");
    // alert("drop");
	$(".drop").each( function(){
		var accept = arrayAnsDrop[$(this).attr('id')];//.split(" ")[0];
		//alert("-"+accept+"-");
		$(this).droppable({
			accept: "."+accept +", #"+accept,
			tolerance: "touch",
			activeClass: 'droppable-active',
			hoverClass: 'droppable-hover',
			drop: function(ev,ui) {
					$(this).empty();
					//BEGIN TWEAK FEEDBACK APPEARING IN DRAGGABLE BLOCKS
					ui.draggable.find('.feedback').css({display:"none"});
					$(".block").find('.feedback').css({display:"none"});
					//END TWEAK
					$(this).html(ui.draggable);
					ui.draggable.addClass('used');
					lastFound=true;
					watchAnswerGroups();
			}
		})
	});
	
	$(".drop-camo").each( function(){
		var ans_accepted = "";
		var count = 0;
		var separator="";
		// alert("drop-camo");
		if(arrayAnsDrop[$(this).attr('id')]){
			var ans_dropzone = arrayAnsDrop[$(this).attr('id')].split(" ");
			for(i=0; i < ans_dropzone.length - 1; i++  )
				ans_accepted+=  "#"+ans_dropzone[i]+", ";
		}
		//var ans_accepted = "."+arrayAnsDrop[$(this).attr('id').split(" ")];
		$(this).droppable({
			accept: ans_accepted,
			tolerance: "touch",
			activeClass: 'droppable-active',
			hoverClass: 'droppable-hover',
			drop: function(ev,ui) {
				if( !isExoType("tableSort") && !isExoType("directedPairAbacus") 
					&& $('#mode').text()!="single"  
				){
					// alert("1st type");getExoType();
					var object = ui.draggable.clone();
					object.draggable('disable');
					object.css({position:'relative'});
					//BEGIN TWEAK FEEDBACK APPEARING IN DRAGGABLE BLOCKS
					object.find('.feedback').css({display:"none"});
					$(".block-i").find('.feedback').css({display:"none"});
					//END TWEAK
					
					if(count==0) separator=""; else if(count%4==0) separator=",<br/><br/>"; else separator=", ";
					count++;
					$(this).append(separator)
					$(this).append(object);
					
					ui.draggable.draggable('disable');
					ui.draggable.draggable('option', 'revert', false);
					ui.draggable.addClass('used');
					ui.draggable.removeClass('block');
					
					lastFound=true;
					watchAnswerGroups();
				}else{
					// alert("2nd type");getExoType();
					$(this).append(ui.draggable);
					if(isExoType("directedPairAbacus"))
						$(this).append("<br/>");
					ui.draggable.draggable('disable');
					// ui.draggable.draggable('option', 'revert', false);
					ui.draggable.addClass('used');
					ui.draggable.removeClass('block');
					
					lastFound=true;
					watchAnswerGroups();
				}
			}
		})
	});
}

/*correctMultiDrop = function(){
	var counter = 2;
	var done=false;
	for (key in arrayAnsDrop){
		// alert("working on :"+key);
		var ansForKey = (arrayAnsDrop[key]).split(" ");
		var i =0; // counter to know when to skip line
		for (var pos = 0 ; pos< ansForKey.length; pos++){ //multiple possible answers
			i+=1;
			ans= ansForKey[pos];

			if( ans!="" && !$('#'+ans).is('.used')){
				// alert("checking use count etc");
				var dropSpots = $('#'+ans).attr('dropSpots').toString();
				var dropCount = parseInt($('#'+ans).attr('dropCount'));
				var targetCount = parseInt($('#'+ans).attr('targetCount'));
				var arrayDropSpots = dropSpots.split("&");
				var foundSpot = false;
				for(var j=0; j<arrayDropSpots.length; j++) if(arrayDropSpots[i]==key) foundSpot=true;
				
				if(foundSpot){
					$("#"+key).append( '<div class=" corrected">'+$('#'+ans).html() + "</div>").append( i%counter==0 ? "<br/><br/>" : "");
					targetCount==dropCount ? $('#'+ans).addClass('usedCorrection').draggable("disable") : $('#'+ans).addClass('semiUsed');
				}
			}
		}
	}
}*/

correctDrop = function(){
	var counter = 4;
	if($("#feedbackType").text()=="float") counter=2;
	for (key in arrayAnsDrop){
		if( $("#"+key).text()==".........."){// || $("#"+key).text()==" .........." ) // exercices with gaps, remove dots
			$("#"+key).html("");
			counter=1000;
		}
		
		var ansForKey = (arrayAnsDrop[key]).split(" ");
		var i =0; // counter to know when to skip line
		for (var pos = 0 ; pos< ansForKey.length; pos++){
			i+=1;
			ans= ansForKey[pos];
			if( ans!="" && ans!=null && !$('#'+ans).is('.used')){
				//alert(ans);
				$("#"+key).append( '<div class=" corrected">'+$('#'+ans).html() + "</div>").append( i%counter==0 ? "<br/><br/>" : "");
				$('#'+ans).addClass('usedCorrection').draggable("disable");
			}
			/*if( ans!="" && !$('#'+ans).is('.used')){
				$("#"+key).append( '<div class=" corrected">'+$('#'+ans).html() + "</div>").append( i%counter==0 ? "<br/><br/>" : "");
				$('#'+ans).addClass('usedCorrection').draggable("disable");
				// alert("placing answer");
			}*/
		}
	}
	//alert("finishing up correction");
	$("span.feedback").remove();	
}

/**
	initialises feedback for drag and drop items
*/
initFBDND = function(){
	// $('.block').bind('dragstart', function(ev, ui) {
	//   	$(ui).attr('found', 'false');
	// 	clickOn=true;
	// 	lastFound=false; // <reset> flag to determine if last object was correctly placed, for feedback purposes
	// });
	// 
	// $('.block').bind('dragstop', function(ev, ui) {
	//   	if(!lastFound) feedback( $(".negative", this ).html() , false);
	// 		else feedback( $(".positive", this ).html() , true);
	// 	clickOn=false;
	// 	if(postponeFinalFB){
	// 		finalFeedback();
	// 		postponeFinalFB= false;
	// 	}
	// });
	
	$('.block, .block-i, .block-h').bind('dragstart', function(ev, ui) {
	  	$(ui).attr('found', 'false');
		clickOn=true;
		lastFound=false; // flag to determine if last object was correctly placed, for feedback purposes
	});

	$('.block, .block-i, .block-h').bind('dragstop', function(ev, ui) {
	  	if(!lastFound) feedback( $(".negative", this ).html() , false);
	  	else feedback( $(".positive", this ).html() , true);
		clickOn=false;
		if(postponeFinalFB){
			finalFeedback();
			postponeFinalFB= false;
		}
	});
}

initMultiDrop = function(){
	
    initDropCommon();
	// alert("multi drop");
	initFBDND();

	$(".drop-camo").each( function(){
		var count = 0;
		var ans_accepted = "";
		var separator="";
		var currentId= $(this).attr('id');
		if(arrayAnsDrop[$(this).attr('id')]){
			var ans_dropzone = arrayAnsDrop[currentId].split(" ");
			for(i=0; i < ans_dropzone.length - 1; i++  )
				ans_accepted+="#"+ans_dropzone[i]+", ";
		}
		//alert(ans_accepted);
		$(this).droppable({
			accept: ans_accepted,
			tolerance: "touch",
			activeClass: 'droppable-active',
			hoverClass: 'droppable-hover',
			drop: function(ev,ui) {
				var dropCount;
				var targetCount;
				var dropSpots = ui.draggable.attr('dropSpots');
				var arrayDropSpots = dropSpots.split("&");
				var foundSpot = false;
				for(var i=0; i<arrayDropSpots.length; i++) if(arrayDropSpots[i]==currentId) foundSpot=true;
				lastFound=true;
				
				if(!foundSpot){
					dropSpots+=currentId+"&";
					dropCount = parseInt(ui.draggable.attr('dropCount')) + 1;
					targetCount = parseInt(ui.draggable.attr('targetCount'));
					
					ui.draggable.attr('dropCount', dropCount);
					ui.draggable.attr('dropSpots', dropSpots);
					var object = ui.draggable.clone();
					object.draggable('disable');
					
					// alert(ui.draggable.attr('dropSpots')[currentId] + " ,"+ui.draggable.attr('targetCount'));

					//object.css({position:'relative'});
					if(count==0) separator=""; else if(count%2==0) separator=",<br/><br/>"; else separator=", ";
					count++;
					$(this).append(separator)
					$(this).append(object);

					
					if(dropCount == targetCount)
						ui.draggable.draggable('disable').addClass('used');
								// 
								// ui.draggable.attr('dropCount', dropCount);
								// var object = ui.draggable.clone();
								// object.draggable('disable');
								// // alert(ui.draggable.attr('dropCount')+ " ,"+ui.draggable.attr('targetCount'));
								// 
								// //object.css({position:'relative'});
								// if(count==0) separator=""; else if(count%2==0) separator=",<br/><br/>"; else separator=", ";
								// count++;
								// $(this).append(separator)
								// $(this).append(object);
								// 
								// lastFound=true;
								// if(dropCount == targetCount){
								// 	ui.draggable.draggable('disable').addClass('used');
				}
				//$(ui).attr('found', 'true');
			}
		})
	});
}


/**************************************
// drag and drop onto image
/**************************************/
initImageDrop = function(){
	
	$('map').each(function(){
		var mapid = $(this).attr("name");
		var imgOffset;
		$("img[usemap='#" + mapid + "']").each(function(){
			 imgOffset = $(this).offset();
		});
		
		$('area', this).each(function(){
			var coords = $(this).attr('coords').split(",");
			var id= $(this).attr('id');
			
			appendArea(imgOffset, {"x1": coords[0], "y1":coords[1],"id":id, "withClass": "note drop-camo"});
		});

	});
	$('map').remove();
	
}

function appendArea(imgOffset, note_data ){
	
	note_left  = parseInt(imgOffset.left) + parseInt(note_data.x1);
	note_top   = parseInt(imgOffset.top) + parseInt(note_data.y1);
	index = parseInt(note_data.pos);
	note_p_top = note_top + parseInt(note_data.height)+5;
					
	note_area_div = $("<div class='"+ note_data.withClass + "'></div>")
			.css({ left: note_left + 'px', top: note_top + 'px'})
			.attr({id: note_data.id}).addClass( index==0 ? "ball-back" : "ball-fore");
	
	// alert("index:"+ index);

	$('#global').append(note_area_div);
}


/**************************************
// spelling and correction
/**************************************/

initCheckSpelling = function(){
	for(var key in arrayAns){
		var tmp_array= key.split(" "); //gives an array with 2+ items : key value
		arrayAnsDrop[tmp_array[1]] = tmp_array[0];
	}
	
	$(".gap").each( function(){
		var pos = $('.positive', this).html();
		var neg = $('.negative', this).html();
		var ans = (arrayAnsDrop[$(':input', this).attr('id')] ).toLowerCase();
		var key = $(this).attr("id");
		
		$(':input', this).keyup(function(event) {
			var guess = this.value.toLowerCase() ;
			if(guess == ans || guess.split(" ")[0]==ans ){
				doSuccess($(this));
				feedback(pos, true);
				watchAnswerGroups();
			}
			else if(guess.length >= ans.length ){
				/*if(compareStrings(ans, guess) == ans){
					this.value= ans;
					doSuccess($(this));
					feedback(pos, true);
				}
				else{*/
					var replacedText ="";
					for( var i = 0; i< ans.length; i++){
						if( guess.charAt(i)==ans.charAt(i)){
							replacedText +=guess.charAt(i);
						}
						else{
							replacedText +="*";
						}
					}
					this.value=replacedText;
					doFail($(this));
					feedback(neg, false);
				//}
			}
			else if(this.value.length< ans.length - 1){
				
			}
			else{ 
				doFail($(this));
				feedback(neg, false);
			}
		});
	});
	
}

compareStrings = function(answer, guess){
	// similarity check algorythm
    var i = 0;
    var j = 0;
    var orders = [[answer, guess], [guess, answer]];
    var maxMisses = Math.floor(answer.length / 6) + 1;
    var misses = 0;
    if (guess.length <= maxMisses) {
        misses = Math.abs(guess.length - answer.length);
        for (i = 0; i < guess.length; i++ ) {
            if (answer.search(guess[i]) == -1) {
                misses += 1;
            }
        }
        if (misses <= maxMisses) {
            return answer;
        } else {
            return guess;
        }
    }
    // Iterate through the different orders of checking
    for (i = 0; i < 2; i++) {
        var string1 = orders[i][0];
        var string2 = orders[i][1];
        while (string1) {
            misses = Math.floor(
                        (Math.abs(string1.length - string2.length) +
                         Math.abs(guess.length - answer.length)) / 2)
            var max = Math.min(string1.length, string2.length)
            for (j = 0; j < max; j++) {
                var a = string2.charAt(j);
                var b = string1.charAt(j);
                if (a != b)
                    misses += 1;
                if (misses > maxMisses)
                    break;
            }
            if (misses <= maxMisses)
                // You are right
                return answer;
            string1 = string1.substr(1);
        }
    }
    // You are wrong!
    return guess;
}

correctSpelling = function(){
	arrayAnsDrop = {};
	for(var key in arrayAns){
		var tmp_array= key.split(" "); //gives an array with 2+ items : key value
		arrayAnsDrop[tmp_array[1]] = tmp_array[0];
	}
	
	for(var key in arrayAnsDrop){
		if(	!$("#"+key).is('.success')){
			$("#"+key).parent().text(arrayAnsDrop[key]).addClass('corrected');
		}
		
		//$("#"+key).remove();
	}
	
}

/**************************************
// matching
/**************************************/

initMatching = function(){
	
	$('.matchbox').append("<div class='matchboxleft'></div><div id='answergroup' class='matchboxright'></div>");
	
	$('div.matchstart').each( function(){
		var clone= $(this).clone();
		$(clone).appendTo('.matchboxleft');
		// $(this).addClass("invisible");
		$(this).remove();
		
		$(clone).click(function(ev){
			clickOn=true;
			clickFlag = $(this).attr('id');
			clickObj = $(this);
			$('.matchstart').removeClass('selected');
			$(this).addClass('selected');
			
			mouseX = ev.pageX;
			mouseY = ev.pageY;
		})
	});
	
	$('.matchend').each(function(){
		var clone= $(this).clone();
		$(clone).appendTo('.matchboxright');
		//$(this).addClass("invisible");
		$(this).remove();
		
		$(clone).click(function(ev){
			if(clickOn){
				$('.matchstart').removeClass('selected');
				clickOn =false;
				// alert( "-"+arrayAnsDrop[$(this).attr('id')]+"-" );
				// alert("-"+clickFlag+"-");
				if( arrayAnsDrop[$(this).attr('id')].split(" ")[0] == clickFlag ){
					$('body').drawPolyline([mouseX, ev.pageX ], [mouseY,ev.pageY], {color:'#222', alpah:1});
					$(this).addClass('found');
					$(clickObj).addClass('found');
					$(clickObj).click(function(){});
				}
				else{
				}
			}
			else{

			}
			watchAnswerGroups();
		})
	});
	
	$('.matchboxleft').children().sort(function(a, b) { 
		var rand=Math.floor(Math.random()*2) - Math.floor(Math.random()*2);
		return rand;
		}).prependTo('.matchboxleft'); 

	$('.matchboxright').children().sort(function(a, b) { 
		var rand=Math.floor(Math.random()*2) - Math.floor(Math.random()*2);
		return rand;
		}).prependTo('.matchboxright');
	
}


initCorrection = function(){
	$("#correct").submit(function(){
		if(isExoType("fill-in")){
			correctSpelling();
		}
		if(isExoType("inline")){
			correctInline();
		}
		if(isExoType("multipleChoice")){
			correctMultiChoice();
		}
		if(isExoType("directedPair") 
			|| isExoType("tableSort") || isExoType("directedPairMatching")
			|| isExoType("imageMatch") || isExoType("directedPairAbacus")) {
			//correctDrop();
			watchAnswerGroups();
		}
		if(isExoType("directedMatch")){
			correctDrop();//correctMultiDrop();
			watchAnswerGroups();
		}
		return false;
	});
}

initVerification = function(){
		$("#verification").submit(function(){
			finalFeedback();
			return false;
		});
	
}

/**************************************
// flash external file (lang) parametering
/**************************************/

function getSWF(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
	return window[movieName];
	} else {
	return document[movieName];
	}
}

isReady = function(){
	return true;
}
initParamFlash = function(){
	// $('.flash-media').each(function(){
	// 	var filename= $(this).attr("name");
	// 	var flashobj = $('object', this).attr('id');
	// 	
	// 	//getSWF(flashobj).setLangFile("http://localhost/babel-data/flash/"+filename);
	// 
	// 	$('#flash-start').click(function(){
	// 		getSWF(flashobj).setLangFile("http://localhost/babel-data/flash/"+filename);
	// 	});
	// });
	
}

/**************************************
// helpers
/**************************************/

doSuccess = function(theobject){
	$(theobject).addClass('success');
	$(theobject).removeClass('fail');
}

doFail = function(theobject){
	$(theobject).addClass('fail');
	$(theobject).removeClass('success');
}

doNeutral = function(theobject){
	$(theobject).removeClass('fail');
	$(theobject).removeClass('success');
}


jQuery.fn.alternateRowColors = function() { 
  $('tbody tr:odd', this).removeClass('even').addClass('odd'); 
  $('tbody tr:even', this).removeClass('odd').addClass('even'); 
  return this; 
}; 


initTableSort = function(){
	$('table.sortable').each(function() { 
		$(this).css({ float:'left'});
   		var $table = $(this); 
		var rows = $table.find('tbody > tr').get(); 

		$.each(rows, function(index, row) { 
		  row.sortKey = $(row).children('td').text().toUpperCase(); 
		}); 
		
		rows.sort(function(a, b) { 
		  if (a.sortKey < b.sortKey) return -1; 
		  if (a.sortKey > b.sortKey) return 1; 
		  return 0; 
		}); 
		
		$.each(rows, function(index, row) { 
		  $table.children('tbody').append(row); 
		  row.sortKey = null; 
		}); 
		
		jQuery.fn.alternateRowColors($table); 

	});
}

/**************************************
// debug helpers
/**************************************/

debugThis = function(item, times){
	var times = (times==null)? 1 : times;
	if(!debugHelper && debugDispCount<times){
		debugDispCount++;
		if(debugDispCount == times)
			debugHelper = true;
		alert(item);
	}
}
